package com.cgq.pro.dao.impl;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.cgq.base.dao.impl.BaseDaoImpl;
import com.cgq.pro.dao.AttachmentDao;
import com.cgq.pro.entity.Attachment;

@Repository
public class AttachmentDaoImpl extends BaseDaoImpl<Attachment> implements
		AttachmentDao {

	@SuppressWarnings("unchecked")
	public List<Attachment> findByBusinessIdAndTypeAndId(String businessId,
			String businessType,String refId) {
		String hql=" FROM Attachment a WHERE a.businessId='"+businessId+"'" +
				" AND a.businessType='"+businessType+"'AND a.refId='"+refId+"'";
		List<Attachment> list=new ArrayList<Attachment>();
		list=hibernateTemplate.find(hql);
		return list;
	}

	public boolean deleteAndPhoto(final String id,final String path) {
		final String hql="DELETE FROM Attachment a WHERE a.id='"+id+"'";
		String str=hibernateTemplate.execute(new HibernateCallback<String>() {
			public String doInHibernate(Session session) throws HibernateException,
					SQLException {
				Transaction transaction=session.beginTransaction();
				String flag="false";
				try{
					transaction.begin();
					Attachment attachment=find(id);
					//1.先删除照片
					File file=new File(path+attachment.getFilePath());
					if(file.exists()){
						file.delete();
					}
					//2.再删除附件记录
					Query query=session.createQuery(hql);
					query.executeUpdate();
					transaction.commit();
					flag="true";
				}catch (Exception e) {
					flag="false";
					transaction.rollback();
				}
				
				return flag;
			}
		});
		return Boolean.parseBoolean(str);
	}

	public boolean deleteAndAttachment(final String[] ids,final String path) {
		String str=hibernateTemplate.execute(new HibernateCallback<String>() {
			public String doInHibernate(Session session) throws HibernateException,
					SQLException {
				Transaction transaction=session.beginTransaction();
				String flag="false";
				try{
					transaction.begin();
					
					Attachment attachment=null;
					for (String id : ids) {
						//1.先删除照片
						attachment=find(id);
						File file=new File(path+attachment.getFilePath());
						if(file.exists()){
							file.delete();
						}
						//2.再删除附件记录
						String hql="DELETE FROM Attachment a WHERE a.id='"+id+"'";
						Query query=session.createQuery(hql);
						query.executeUpdate();
					}
					transaction.commit();
					flag="true";
				}catch (Exception e) {
					flag="false";
					transaction.rollback();
				}
				return flag;
			}
		});
		return Boolean.parseBoolean(str);
	}
	
}
